package com.soul.dubbo.api.mongo;

import com.soul.dubbo.utils.IdWorker;
import com.soul.model.mongo.Video;
import com.soul.model.vo.PageResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * @author mdoya
 * @version 1.0
 * @description:
 */
@Slf4j
@DubboService
public class SmallVideoApiImpl implements SmallVideoApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private IdWorker idWorker;

    /**
     * 发布小视频
     *
     * @param video 视频对象
     */
    @Override
    public void addVideo(Video video) {
        // 1. vip字段主要大数据推荐
        video.setVid(idWorker.getNextId("video"));
        // 2. 时间毫秒值
        video.setCreated(System.currentTimeMillis());
        // 3. 执行语句
        mongoTemplate.insert(video);
    }

    /**
     * 查询小视频列表分页
     *
     * @param videoIdsList 小视频ids
     * @param page         码数
     * @param pagesize     每页条数
     * @return PageResult<Video>
     */
    @Override
    public PageResult<Video> findByIdsAndCondition(List<Long> videoIdsList, Long page, Long pagesize) {
        // 1. 查询总条数
        Query query = new Query();
        long count = mongoTemplate.count(query, Video.class);
        // 2. 公共方法 videoIdsList为空时设置分页条件
        if (CollectionUtils.isEmpty(videoIdsList)){
            query.skip((page - 1) * pagesize).limit(pagesize.intValue());
        } else {
            query.addCriteria(Criteria.where("vid").in(videoIdsList));
        }
        query.with(Sort.by(Sort.Direction.DESC,"created"));
        // 3. 执行查询构造参数返回
        return new PageResult<>(page,pagesize,count,mongoTemplate.find(query, Video.class));
    }

    @Override
    public PageResult findByUserId(Long page, Long pagesize, Long userId) {
        Query query = Query.query(Criteria.where("userId").in(userId));
        long count = mongoTemplate.count(query, Video.class);
        query.limit(pagesize.intValue()).skip((page -1) * pagesize)
                .with(Sort.by(Sort.Order.desc("created")));
        List<Video> list = mongoTemplate.find(query, Video.class);
        return new PageResult(page,pagesize,count,list);
    }
}
